package com.tool_stdy.ForkJoinDemo;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

/**
 * Created by yan_li on 2016/1/25.
 */
public class ForkJoinTest extends RecursiveTask<Integer> {

    private int begin;
    private int end;

    private int sum=0;
    ForkJoinTest(int begin,int end){
        this.begin=begin;
        this.end=end;
    }
    @Override
    protected Integer compute() {
        if(end-begin>100){
            System.out.println(Thread.currentThread().getName()+"Go");
            for(int i= begin;i<end;i++){
                sum+=i;
            }
        }else {
            int mid =(end+begin)/2;
            ForkJoinTest left = new ForkJoinTest(begin,mid);
            ForkJoinTest right = new ForkJoinTest(mid,end);
            right.fork();
            left.fork();
            sum +=left.join()+right.join();
        }
        return sum;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        Future<Integer> result = forkJoinPool.submit(new ForkJoinTest(0, 2000));
        System.out.println(result.get());
    }
}
